package kava.framework.lcdui;

import java.util.Vector;

import javax.microedition.lcdui.Graphics;

public class ContainerForm extends Form {
	protected Vector widgets;
	public static final int INVALID_CHILD_INDEX = -1;

	public ContainerForm() {
		widgets = new Vector();

	}

	protected final void addWidget(Widget widget) {
		widgets.addElement(widget);
	}

	protected final boolean isEmpty() {
		return widgets.size() > 0;
	}

	protected final int getChildIndexByID(int id) {
		int count = widgets.size();
		for (int i = 0; i < count; i++) {
			Widget child = (Widget) widgets.elementAt(i);
			if (child.ID == id) {
				return i;
			}
		}
		return INVALID_CHILD_INDEX;
	}

	public final Widget getChildByID(int id) {
		int index = getChildIndexByID(id);
		if (index != INVALID_CHILD_INDEX) {
			return (Widget) widgets.elementAt(index);
		}
		return null;
	}

	// x,y relative to screen
	protected final Widget getChildByPos(int x, int y) {
		int count = widgets.size();
		int x2 = x - this.x;
		int y2 = y - this.y;
		for (int i = 0; i < count; i++) {
			Widget child = (Widget) widgets.elementAt(i);
			if (child.cover(x2, y2)) {
				return child;
			}
		}
		return null;
	}

	protected final void onUpdateWidget(int wid) {
		Widget child = getChildByID(wid);
		if (child != null) {
			Graphics g = KavaFrame.getGraphics() ;
			if (g != null) {
				child.paint(g);
				KavaFrame.freeGraphics();
				KavaFrame.invalideRec(x + child.x, x + child.y, child.width,
						child.height);
			}

		}

	}

	protected void onWidgetPressed(int widgetID) {

	}

	protected void onWidgetReleased(int widgetID) {

	}

	public void setFocusChildByID(int id) {
		int count = widgets.size();
		for (int i = 0; i < count; i++) {
			Widget child = (Widget) widgets.elementAt(i);
			if (child.ID == id) {
				child.state = Widget.STATE_FOCUSED;
			} else {
				child.state = Widget.STATE_NORMAL;
			}
		}
	}

	protected void paint(Graphics g) {
		super.paint(g);
		int count = widgets.size();
		for (int i = 0; i < count; i++) {
			Widget child = (Widget) widgets.elementAt(i);
			child.paint(g);
		}
	}

	protected void onPenDown(int x, int y) {
		Widget widget = getChildByPos(x, y);
		if (widget != null && widget.visual) {
			setFocusChildByID(widget.ID);
			onWidgetPressed(widget.ID);
		}
	}

	protected void onPenUp(int x, int y) {
		Widget widget = getChildByPos(x, y);
		if (widget != null) {
			onWidgetReleased(widget.ID);
		}
	}

	protected int getFocusChildID() {
		int count = widgets.size();
		for (int i = 0; i < count; i++) {
			Widget child = (Widget) widgets.elementAt(i);
			if (child.state == Widget.STATE_FOCUSED
					|| child.state == Widget.STATE_PRESSED) {
				return child.ID;
			}
		}
		return INVALID_CHILD_INDEX;
	}

}
